package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService  seckillVoucherService;

    @Resource
    private RedisIdWorker  redisIdWorker;
     @Resource
     private StringRedisTemplate stringRedisTemplate;
     @Resource
     private RedissonClient redissonClient;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT ;// LUA脚本
    static {//  静态代码块
        SECKILL_SCRIPT = new DefaultRedisScript<>();//  创建脚本
        //SECKILL_SCRIPT.setLocation((org.springframework.core.io.Resource) new ClassPathResource("seckill.lua"));// 指定脚本位置
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);//  返回结果类型
    }

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);//  创建阻塞队列
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();// 创建线程池

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();//不能用UserHolder.getUser()取因为不是一个线程
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean b = lock.tryLock();
        if(!b){
            //获取锁失败，直接返回失败或者重试
            log.error("获取锁失败");
            return;
        }try{
            proxy.createVoucherOrder(voucherOrder);//拿到一个线程的代理对象
        }finally {
            lock.unlock();
        }
    }

    private IVoucherOrderService  proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        //执行脚本
        UserDTO user = UserHolder.getUser();
//        if (user == null) {
//            return Result.fail("请先登录");
//        }
        Long userId = user.getId();
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());
        Long r = result;
        if(r != 0){
            //不为0，则说明没有购买成功
            return Result.fail(r==1?"库存不足":"已抢购过");
        }

        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        Long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        Long id = UserHolder.getUser().getId();
        voucherOrder.setUserId(id);
        voucherOrder.setVoucherId(voucherId);
        //放到阻塞队列中
        orderTasks.add(voucherOrder);

        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //  1.查询优惠券
//        SeckillVoucher byId = seckillVoucherService.getById(voucherId);
//        //  2.判断秒杀是否开始
//        if (byId.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始");
//        }
//        //  3.判断秒杀是否结束
//        if (byId.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束");
//        }
//        //  4.判断库存是否充足
//        if (byId.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        return createVoucherOrder(voucherId);
//
//    }
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherId) {
        //一人一单
        Long userId = voucherId.getUserId();

        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return ;
        }
        //  5.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId).gt("stock", 0)
                .update();
        if (!success) {
            return ;
        }

        save(voucherId);
    }



//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        //一人一单
//        Long userId = UserHolder.getUser().getId();
//
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        boolean isLock = lock.tryLock();
//
//        if (!isLock) {
//            return Result.fail("不允许重复下单");
//        }
//        try {
//
//            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//            if (count > 0) {
//                return Result.fail("用户已经购买过");
//            }
//            //  5.扣减库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock = stock - 1")
//                    .eq("voucher_id", voucherId).gt("stock", 0)
//                    .update();
//            if (!success) {
//                return Result.fail("库存不足");
//            }
//            //  6.创建订单
//            VoucherOrder voucherOrder = new VoucherOrder();
//            Long orderId = redisIdWorker.nextId("order");
//            voucherOrder.setId(orderId);
//            Long id = UserHolder.getUser().getId();
//            voucherOrder.setUserId(id);
//            voucherOrder.setVoucherId(voucherId);
//            save(voucherOrder);//  保存订单
//
//            return Result.ok(orderId);
//        } finally {
//            lock.unlock();
//        }
//
//
//
//    }
}
